<template>
  <div class="hours-weather">
    <px-radio-group v-model="tab" class="hours-weather-tab" @change="handleTabChange">
      <px-radio-button label="temp">气温</px-radio-button>
      <px-radio-button label="windScale">风力</px-radio-button>
      <px-radio-button label="humidity">相对湿度</px-radio-button>
      <px-radio-button label="precip">降水量</px-radio-button>
      <px-radio-button label="pressure">大气压</px-radio-button>
      <px-radio-button label="wetBulbTemp">湿球温度</px-radio-button>
      <px-radio-button label="enthalpy">焓值</px-radio-button>
      <px-radio-button label="dew">露点</px-radio-button>
    </px-radio-group>
    <HoursBox :noStripe="tab === 'precip'" class="mt-[16px]" :dateTime="dateTime" :data="houtrs">
      <!-- 气温 -->
      <div v-if="tab === 'temp'">
        <px-row>
          <px-col v-for="item in hoursData" :key="item.fxTime" :span="1">
            <px-tooltip :content="item.text">
              <div class="icon"><i :class="`qi-${item.icon}`" /></div>
            </px-tooltip>
          </px-col>
        </px-row>
        <div id="chart" ref="chartRef" />
      </div>
      <!-- 风力 -->
      <div v-if="tab === 'windScale'">
        <px-row>
          <px-col v-for="item in hoursData" :key="item.fxTime" :span="1">
            <div :class="['wind-icon', getWindDir(item.windDir)].join(' ')">
              <svg
                v-if="getWindDir(item.windDir)"
                viewBox="0 0 24 24"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                xmlns:xlink="http://www.w3.org/1999/xlink"
              >
                <g id="工作台" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">
                  <g id="天气预报2.0（类型切换）" transform="translate(-483, -466)" fill="#3B82F6" fill-rule="nonzero">
                    <g id="01备份" transform="translate(495, 478) rotate(-180) translate(-495, -478)translate(483, 466)">
                      <path
                        id="形状"
                        d="M12.0782208,0 C12.4041871,0.000428025832 12.766369,0.250272781 12.8610749,0.627357445 L21.4724701,22.584868 C21.5569249,23.0464646 21.4455398,23.4901084 21.1593285,23.8395829 C20.8109949,24.0331128 20.3574415,24.0729084 20.0633327,23.8395829 L11.92165,19.1344021 L3.9365381,23.8395829 C3.6414493,24.0729764 3.18852428,24.0329359 2.84054234,23.8395829 C2.55470276,23.4905656 2.44316531,23.0475872 2.5274007,22.584868 L11.1387959,0.627357445 C11.233384,0.249853983 11.5959939,0 12.0782208,0 Z M5.50224631,20.859635 L11.6085084,17.2523297 C11.888316,17.0858067 12.2682356,17.0857615 12.5479333,17.2523297 L18.6541953,20.859635 L12.0782208,3.76414467 L5.50224631,20.859635 Z"
                      />
                    </g>
                  </g>
                </g>
              </svg>
              <span v-else>-</span>
            </div>
            <div class="center windScale">{{ item.windScale }}级</div>
            <div class="center windDir">{{ item.windDir }}</div>
          </px-col>
        </px-row>
      </div>
      <!-- 其他 -->
      <div v-if="['precip', 'humidity', 'wetBulbTemp', 'enthalpy', 'dew', 'pressure'].includes(tab)" class="chart-box">
        <div id="chart" ref="chartRef" class="chart-container cover" />
      </div>
    </HoursBox>
  </div>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, nextTick } from "vue";
import HoursBox from "../HoursBox/index.vue";
import dayjs from "dayjs";
import * as echarts from "echarts";
import { queryWeatherHourly, queryHistoryWeatherHourly } from "@/api/bench";
const tab = ref("temp");
const hoursData = ref([]);
const houtrs = ref([]);
const getWindDir = windDir => {
  if (windDir === "北风") {
    return "n";
  }
  if (windDir === "东北风") {
    return "ne";
  }
  if (windDir === "东风") {
    return "e";
  }
  if (windDir === "东南风") {
    return "se";
  }
  if (windDir === "南风") {
    return "s";
  }
  if (windDir === "西南风") {
    return "sw";
  }
  if (windDir === "西风") {
    return "w";
  }
  if (windDir === "西北风") {
    return "nw";
  }
};
const chartRef = ref();
let echartInstance: any = null;
// 折线图
const getLineChart = (key, unit) => {
  if (echartInstance) {
    echartInstance?.dispose();
    echartInstance = null;
    window.removeEventListener("resize", handelResize);
  }
  // const ele = document.getElementById("chart");
  echartInstance = echarts.init(chartRef.value);
  const data = hoursData.value.map(item => Number(item[key]));
  const startValue = Math.min(...data);
  const max = Math.max(...data);
  const options = {
    xAxis: {
      type: "category",
      show: false
      // boundaryGap: false // 关键：使数据点居中
    },
    grid: {
      top: "24px",
      left: 0,
      bottom: 0,
      right: 0
    },
    yAxis: {
      type: "value",
      show: false,
      max,
      startValue
    },
    series: [
      {
        data,
        type: "line",
        smooth: true,
        areaStyle: {
          origin: "start",
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(109, 184, 251, 0)" // 0% 处的颜色
              },
              {
                offset: 1,
                color: "rgba(59, 130, 246, 0.32)" // 100% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        },
        lineStyle: {
          width: 1,
          color: "rgba(0, 97, 255, 1)"
        },
        itemStyle: {
          color: "rgba(0, 97, 255, 1)"
        },
        label: {
          show: true,
          formatter: `{c}${unit}`,
          fontWeight: "500",
          fontSize: "16px"
        }
      }
    ]
  };
  echartInstance.setOption(options);
  window.addEventListener("resize", handelResize);
}; // 动态生成与每个柱子等宽的横线
const addHorizontalLines = chartInstance => {
  const option = chartInstance.getOption();
  const series = option.series[0];
  const barGap = (chartInstance.getWidth() / 24) * 0.4; // 计算柱子的实际宽度
  const graphicElements = [];

  series.data.forEach((value, index) => {
    const point = chartInstance.convertToPixel({ seriesIndex: 0 }, [option.xAxis[0].data[index], value]);
    const x = point[0] - barGap; // 横线起始x坐标
    const y = point[1]; // 横线y坐标

    graphicElements.push({
      type: "line",
      shape: {
        x1: x,
        y1: y,
        x2: x + barGap * 2, // 线条长度等于柱子宽度
        y2: y
      },
      style: {
        stroke: "rgba(0, 97, 255, 1)", // 线条颜色
        lineWidth: 4 // 线条宽度
      },
      z: 100 // 确保线条在柱子上方
    });
  });
  option.graphic = graphicElements;
  chartInstance.setOption(option);
};
// 柱状图
const getBarChart = (key, unit) => {
  if (echartInstance) {
    echartInstance?.dispose();
    echartInstance = null;
    window.removeEventListener("resize", handelResize);
  }
  echartInstance = echarts.init(chartRef.value);
  const data = hoursData.value.map(item => Number(item[key]));

  const option: any = {
    xAxis: {
      type: "category",
      show: false,
      data: Object.keys(data)
    },
    grid: {
      top: "24px",
      left: 0,
      bottom: 0,
      right: 0
    },
    yAxis: {
      type: "value",
      show: false
    },
    series: [
      {
        data: data,
        type: "bar",
        barWidth: "80%",
        barCategoryGap: "5px",
        animation: false,
        itemStyle: {
          origin: "start",
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(109, 184, 251, 0)" // 0% 处的颜色
              },
              {
                offset: 1,
                color: "rgba(59, 130, 246, 0.32)" // 100% 处的颜色
              }
            ],
            global: false // 缺省为 false
          }
        },
        label: {
          show: true,
          formatter: `{c}${unit}`,
          fontWeight: "500",
          fontSize: "16px",
          position: "top",
          color: "#000"
        }
      }
    ],
    graphic: []
  }; // 动态计算每个柱子顶部横线的位置和长度
  echartInstance.setOption(option);
  // 初始化图表后调用该函数
  // echartInstance.on("finished", () => {
  addHorizontalLines(echartInstance);
  window.addEventListener("resize", handelResize);
  // });
};
const renderChart = () => {
  nextTick(() => {
    if (tab.value === "temp") {
      getLineChart(tab.value, "℃");
    }
    if (tab.value === "precip") {
      getBarChart(tab.value, "mm");
    }
    if (tab.value === "humidity") {
      getLineChart(tab.value, "%");
    }
    if (tab.value === "wetBulbTemp") {
      getLineChart(tab.value, "℃");
    }
    if (tab.value === "enthalpy") {
      getLineChart(tab.value, "kj/kg");
    }
    if (tab.value === "dew") {
      getLineChart(tab.value, "℃");
    }
    if (tab.value === "pressure") {
      getLineChart(tab.value, "hPa");
    }
  });
};
const handleTabChange = () => {
  renderChart();
};
const handelResize = () => {
  if (echartInstance) {
    echartInstance.resize();
  }
};
const props = defineProps(["dateTime", "type"]);
const getWeatherHourly = async () => {
  let data = null;
  if (props.type === "history") {
    data = await queryHistoryWeatherHourly(props.dateTime);
  } else {
    data = await queryWeatherHourly(props.dateTime);
  }
  hoursData.value = data || [];
  houtrs.value = hoursData.value.map(item => {
    const time = dayjs(item.fxTime).format("HH:00");
    return time;
  });

  handleTabChange();
};
onMounted(() => {
  if (props.dateTime) {
    getWeatherHourly(props.dateTime);
  }
});
watch([() => props.dateTime, () => props.type], () => {
  if (props.dateTime) {
    getWeatherHourly(props.dateTime);
  }
});
onUnmounted(() => {
  window.removeEventListener("resize", handelResize);
});
</script>
<style lang="scss" scope>
.hours-weather-tab {
  justify-content: center;
  width: 100%;
}

#chart {
  width: 100%;
  height: 84px;
}

.chart-box .chart-container.cover {
  height: 120px !important;
}

.icon {
  font-size: 24px;
  color: rgb(59 130 246 / 100%);
  text-align: center;
}

.center {
  text-align: center;
}

.wind-icon {
  width: 24px;
  height: 24px;
  margin: 0 auto;
  margin-top: 8px;
  line-height: 24px;
  color: rgb(59 130 246 / 100%);
  text-align: center;
}

.n {
  transform: rotateZ(0deg);
}

.ne {
  transform: rotateZ(45deg);
}

.e {
  transform: rotateZ(90deg);
}

.se {
  transform: rotateZ(135deg);
}

.s {
  transform: rotateZ(180deg);
}

.sw {
  transform: rotateZ(225deg);
}

.w {
  transform: rotateZ(270deg);
}

.nw {
  transform: rotateZ(315deg);
}

.windScale {
  margin-top: 18px;
  font-size: 16px;
  font-weight: bold;
  line-height: 22px;
  color: #000;
}

.windDir {
  margin-top: 18px;
  font-size: 14px;
  line-height: 20px;
  color: #000;
}
</style>
